package com.jzy.gulimall.authserver.controller;

import cn.hutool.core.lang.TypeReference;
import com.jzy.common.constant.AuthServerConstant;
import com.jzy.common.constant.CartConstant;
import com.jzy.common.exception.BizCodeEnum;
import com.jzy.common.utils.CookieUtil;
import com.jzy.common.utils.R;
import com.jzy.common.vo.MemberRespVo;
import com.jzy.gulimall.authserver.feign.CartFeignService;
import com.jzy.gulimall.authserver.feign.MemberFeignService;
import com.jzy.gulimall.authserver.feign.ThirdPartyFeignService;
import com.jzy.gulimall.authserver.util.PhoneCodeUntil;
import com.jzy.gulimall.authserver.util.RedisUtil;
import com.jzy.gulimall.authserver.vo.UserLoginVo;
import com.jzy.gulimall.authserver.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jzy
 * @date 2020/9/16 17:35
 */
@Controller
public class IndexController {

    @Resource
    private RedisUtil redisUtil;

    /*@GetMapping("/login.html")
    public String loginPage(){
        return "login";
    }

    @GetMapping("/register.html")
    public String registerPage(){
        return "register";
    }*/
    @Resource
    private ThirdPartyFeignService thirdPartyFeignService;

    @Resource
    private MemberFeignService memberFeignService;

    @Resource
    private CartFeignService cartFeignService;

    /**
     * 登录  合并购物车
     */
    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session,HttpServletRequest request) {
        //远程登录
        R login = memberFeignService.login(userLoginVo);
        if (login.getCode() == 0) {
            MemberRespVo data = login.getData(new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            String userKey = CookieUtil.getCookieValue(request, CartConstant.TEMP_USER_COOKIE_NAME, false);
            R r = cartFeignService.mergeCart(userKey, data.getId());
            if (r.getCode() == 0) {
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }
        Map<String, String> errors = new HashMap<>();
        errors.put("msg", (String) login.get("msg"));
        redirectAttributes.addFlashAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/login.html";
    }


    /**
     * 注册
     */
    // TODO: 2020/9/17 分布式session问题
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo userRegisterVo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            Map<String, String> errors = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/register.html";
//            return "redirect:http://baidu.com";
        }
        //校验验证码
        String code = userRegisterVo.getCode();
        String redisCode = "";
        try {
            // TODO: 2020/9/17 lua脚本 发现即删除
            redisCode = (String) redisUtil.hget("smscode", userRegisterVo.getPhone());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //验证码已失效
        Map<String, String> errors = new HashMap<>();
        if (StringUtils.isBlank(redisCode)) {
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/register.html";
        } else {
            if (code.equalsIgnoreCase(redisCode)) {
                //验证通过  删除验证码
                redisUtil.hdel("smscode", userRegisterVo.getPhone());
                //调用会员服务,进行注册
                R register = memberFeignService.register(userRegisterVo);
                if (register.getCode() == 0) {
                    //成功
                } else {
                    //失败
                    errors.put("code", (String) register.get("msg"));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/register.html";
                }
            } else {
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/register.html";
            }
        }
        //注册成功,重定向登录页面
        return "redirect:http://auth.gulimall.com/login.html";
    }

    /**
     * 注册 发送验证码
     */
    @GetMapping("/sms/sendMessage")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        // TODO: 2020/9/16 接口防刷
        //存入缓存 防止同一个phone在120秒内再次发送
        String redisCode = "";
        try {
            redisCode = (String) redisUtil.hget("smscode", phone);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(redisCode)) {
            //生成6位随机数
            String code = PhoneCodeUntil.getRandomString(6);
            System.out.println("验证码：" + code);
            //存入缓存
            redisUtil.hset("smscode", phone, code, 120);
            return thirdPartyFeignService.sendMessage(phone, code);
        }
        return R.error(BizCodeEnum.SMS_CODE_SEND_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_SEND_EXCEPTION.getMessage());
    }


    /**
     * 去登录页
     */
    @GetMapping("/login.html")
    public String loginPage(HttpServletRequest request, HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            return "redirect:http://gulimall.com";
        }
        return "login";
    }

}
